import './index.less'

const widgets = {
  AppHeader: {
    template: `
      <div class="app-header">
        <div class="inner">
          <slot></slot>
        </div>
      </div>
    `
  },
  AppFooter: {
    template: `
      <div class="app-footer">
        <ul>
          <li
            v-for="(v, idx) in $root.nav.list"
            :key="idx"
            :class="{ on: v.com === $root.router.com }"
            @click="$root.setRouter({ com: v.com })"
          >
            <i :class="['glyphicon glyphicon-' + v.icon]"></i>
            <div class="text">{{ v.name }}</div>
          </li>
        </ul>
      </div>
    `
  },
  ImgUploader: {
    template: `
      <div class="img-uploader">
        <div class="title-bar">
          <div class="auto-flex">{{ title }}</div>
          <div class="text-danger bold">{{ '最多 ' + maxLen + ' 张图' }}</div>
          <div>
            <button class="btn btn-info" type="button"
              @click="() => fileEl.click()"
            >
              <i class="glyphicon glyphicon-plus"></i>
              <span>{{ btnText }}</span>
            </button>
          </div>
        </div>
        <div class="list-upload-imgs">
          <section v-for="(v, idx) in imgs" :key="idx">
            <div class="inner" :style="{ backgroundImage: 'url(' + v.src + ')' }">
              <span
                class="btn btn-xs btn-warning btn-pin"
                v-if="idx > 0"
                @click="imgs.unshift(imgs.splice(idx, 1)[0])"
              >
                <i class="glyphicon glyphicon-pushpin"></i>
              </span>
              <span class="btn btn-xs btn-danger btn-trash" @click="imgs.splice(idx, 1)">
                <i class="glyphicon glyphicon-trash"></i>
              </span>
              <span
                class="btn btn-xs btn-default btn-prev"
                v-if="idx > 0"
                @click="imgs.swap(idx, idx - 1)"
              >
                <i class="glyphicon glyphicon-arrow-left"></i>
              </span>
              <span
                class="btn btn-xs btn-default btn-next"
                v-if="idx < imgs.length - 1"
                @click="imgs.swap(idx, idx + 1)"
              >
                <i class="glyphicon glyphicon-arrow-right"></i>
              </span>
            </div>
          </section>
        </div>
      </div>
    `,
    name: 'img-uploader',
    props: {
      title: {
        type: String,
        default: '上传图片'
      },
      btnText: {
        type: String,
        default: '选择图片'
      },
      maxLen: {
        type: Number,
        default: 6
      },
      accept: {
        type: String,
        default: 'image/*'
      },
      imgs: {
        type: Array,
      }
    },
    methods: {
      async handleFileChange(e) {
        const files = [...e.target.files]
        const imgs = this.imgs

        if (files.length + imgs.length > this.maxLen) {
          vm.alert(`最多添加 ${this.maxLen} 张图`)
        }

        ;(await Promise.all(files.slice(0, this.maxLen - imgs.length).map(async (file) => {
          const { img, blob } = await vm.imgCompress(file)
          return {
            blob,
            width: img.width,
            height: img.height,
            src: img.src,
          }
        }))).forEach(v => imgs.push(v))
      },
      async upload(scope, rowId) {
        const vm = this.$root

        if (!scope) throw new Error('img-uploader error: need scope')
        if (!rowId) throw new Error('img-uploader error: need rowId')

        const arr = this.imgs.filter(v => v.blob)

        for (let i = 0; i < arr.length; i++) {
          const v = arr[i]
          await vm.uploadImg({
            scope,
            rowId,
            jdKey: 'imgs',
            fileName: v.blob.name,
            img: v.blob,
            thumb: (await vm.imgCompress(v.blob, 200)).blob,
          }).then(({ time, hash }) => {
            v.time = time
            v.hash = hash
          })
        }

        return this.imgs.map((v) => {
          return {
            width: v.width,
            height: v.height,
            time: v.time,
            hash: v.hash
          }
        })
      }
    },
    async mounted() {
      const fileEl = (this.fileEl = document.createElement('input'))
      fileEl.type = 'file'
      fileEl.accept = 'image/*'
      fileEl.multiple = true
      fileEl.onchange = this.handleFileChange.bind(this)
    }
  },
  SmartDialog: {
    template: `
      <div v-if="isShow">
        <teleport :to="to">
          <div class="smart-dialog" ref="el"
            @mousedown="handleMouseDown"
          >
            <slot></slot>
          </div>
        </teleport>
      </div>
    `,
    props: {
      isShow: {
        type: Boolean,
        default: false,
      },
      to: {
        type: String,
        default: '#app-main',
      }
    },
    methods: {
      handleMouseDown(e) {
        const { clientX: x1, clientY: y1 } = e

        document.onmouseup = (e) => {
          document.onmousemove = null
          document.onmouseup = null

          const { clientX: x2, clientY: y2 } = e

          if (Math.abs(x2 - x1) > 3 || Math.abs(y2 - y1) > 3) {
            return
          }

          if (
            e.target === this.$refs.el ||
            e.target.closest('.glyphicon-remove, [data-close]')
          ) {
            this.$emit('close')
          }
        }
      }
    },
  },
  SmartLoading: {
    template: `
      <div class="smart-loading">
        <ul>
          <li
            v-for="(n, idx) in len"
            :key="idx"
            :style="{
              transform: 'rotate(' + (idx / len * 360) + 'deg) translateX(180%)',
              backgroundColor: 'hsla(0, 0%, ' + (1 - (idx / (len - 1) * (1 - offset * 2) + offset)) * 100 + '%, 1)'
            }"
          ></li>
        </ul>
      </div>
    `,
    data() {
      return {
        len: 12,
        offset: 0,
      }
    }
  },
}

export default (app) => {
  Object.keys(widgets).forEach((k) => {
    app.component(k, widgets[k])
  })
}